package app.modules.cloudpivot.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.PlatformConfigFacade;
import com.authine.cloudpivot.engine.api.model.dto.MessageDTO;
import com.authine.cloudpivot.engine.api.model.system.SystemSettingModel;
import com.authine.cloudpivot.engine.service.message.IMessageService;
import com.authine.cloudpivot.engine.service.organization.exception.DataSourceException;
import com.zjiecode.wxpusher.client.WxPusher;
import com.zjiecode.wxpusher.client.bean.Message;
import com.zjiecode.wxpusher.client.bean.MessageResult;
import com.zjiecode.wxpusher.client.bean.Result;

/**
 * 自定义消息通道实现
 *
 * @author LiuGangQiang Create in 2024/02/28
 */
@Service
public class WxPusherMessageServiceImpl implements IMessageService {
    private static final Logger log = LoggerFactory.getLogger(WxPusherMessageServiceImpl.class);
    @Autowired
    private PlatformConfigFacade platformConfigFacade;

    @Override
    public List<String> sendMsg(MessageDTO message) throws DataSourceException {
        Map<String, String> configs = getConfig("WxPusher");
        Message wxmessage = new Message();
        wxmessage.setAppToken(configs.get("AppToken"));
        wxmessage.setContentType(Message.CONTENT_TYPE_TEXT);
        wxmessage.setContent(message.getContent());
        wxmessage.setTopicId(Long.parseLong(configs.get("TopicId")));
        wxmessage.setUrl(message.getUrl());
        Result<List<MessageResult>> result = WxPusher.send(wxmessage);
        log.info("===>>WxPusher推送成功：{}", result);
        return null;
    }

    @Override
    public String initChannel() {
        return "WxPusher";
    }

    private Map<String, String> getConfig(String code) {
        SystemSettingModel config = platformConfigFacade.getSystemSettingBySettingCode(code);
        JSONObject jsonObject = JSONObject.parseObject(config.getSettingValue());
        JSONArray parameterList = jsonObject.getJSONArray("parameterlist");
        return parameterList.stream().map(item -> (JSONObject) item).collect(Collectors.toMap(item -> item.getString("code"), item -> item.getString("value")));
    }
}
